import React from 'react';
import styles from './style.less'
import classname from 'classname'

const ranANum = () => {
  return Math.floor( Math.random() * 10 );
};

class RandomLittleNum extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      val: 0
    }
  }



  componentDidMount() {
    this.timer = setInterval( () => {
      this.setState({
        val: ranANum()
      });
    }, 50);
  }



  componentWillUnmount() {
    clearInterval( this.timer )
  }


  render(){
    return(
      <div>
        { this.state.val }
      </div>
    )
  }
}

const POS_ALL_OFF = -1;
const POS_ALL_ON = 7;



// 只要你给我传一个数字， 我就开始慢慢地将其揭晓
class randomNum extends React.Component {
  constructor( props ) {
    super( props );
    this.state = {
      pos: POS_ALL_OFF,
      numArr: Array( 6 ).fill( '?' ),
      numBig: false
    };
  };


  componentDidMount() {
    if( this.props.value ){
      this.reStart();
    }
  }

  componentWillReceiveProps( nextProps ) {
    let { value: newV } = nextProps;
    let { value: oldV } = this.props;
    if ( oldV !== newV ) {
      this.reStart();
    }
  }


  reStart() {
    this.setState({
      pos: POS_ALL_OFF,
      numBig: false
    });


    this.timer = setInterval(() => {
      let { pos } = this.state;
      if ( pos === POS_ALL_ON ){

        clearInterval(this.timer);
      } else if( pos === POS_ALL_ON - 1 ){
        this.props.onFinish( this.props.value );

        this.setState({
          pos:  this.state.pos + 1,
          numBig: true
        });
      }else{
        this.setState({
          pos:  this.state.pos + 1
        });
      }
    }, 1000);

  }


  componentWillUnmount(){
    clearInterval(this.timer);
  }


  render() {
    let { numArr, pos, numBig } = this.state;
    let { value = '' } = this.props;
    let valArr = value.split('');
    let className = classname({
      [styles.luckyNum]: true,
      [styles.numBig]: numBig,
    });

    return(
      <div className={className}>
      {
        numArr.map( ( el, index ) => {
          if ( index < pos ) {
            return <div key={index}>{ valArr[ index ] }</div>;
          } else if ( index === pos ) {
            return <RandomLittleNum key={index}/>
          } else {
            return el
          }
        } )
      }
       </div>
    )

  }
}

export default randomNum;